
import {createElement, findDOMNode, Component} from 'rax';
import View from 'rax-view';
import Picture from 'rax-picture';
import ScrollView from 'rax-scrollview';
import Touchable from 'rax-touchable';
import transition from 'universal-transition';

const defaultModuleData = {
  tabHeight: 100,
  itemHeight: 80,
  itemWidth: 145,
  itemPadding: 10,
  items: [
    {
      modName: 'page1',
      itemCover: '//img.alicdn.com/imgextra/i4/3355153118/TB2UAadhHsTMeJjSsziXXcdwXXa_!!3355153118.jpg',
      itemBack: '//img.alicdn.com/imgextra/i1/3355153118/TB2agOvhHsTMeJjSszhXXcGCFXa_!!3355153118.jpg',
    },
    {
      modName: 'page2',
      itemCover: '//img.alicdn.com/imgextra/i4/3355153118/TB2UAadhHsTMeJjSsziXXcdwXXa_!!3355153118.jpg',
      itemBack: '//img.alicdn.com/imgextra/i1/3355153118/TB2agOvhHsTMeJjSszhXXcGCFXa_!!3355153118.jpg',
    },
    {
      modName: 'page3',
      itemCover: '//img.alicdn.com/imgextra/i4/3355153118/TB2UAadhHsTMeJjSsziXXcdwXXa_!!3355153118.jpg',
      itemBack: '//img.alicdn.com/imgextra/i1/3355153118/TB2agOvhHsTMeJjSszhXXcGCFXa_!!3355153118.jpg',
    },
    {
      modName: 'page4',
      itemCover: '//img.alicdn.com/imgextra/i4/3355153118/TB2UAadhHsTMeJjSsziXXcdwXXa_!!3355153118.jpg',
      itemBack: '//img.alicdn.com/imgextra/i1/3355153118/TB2agOvhHsTMeJjSszhXXcGCFXa_!!3355153118.jpg',
    },
    {
      modName: 'page5',
      itemCover: '//img.alicdn.com/imgextra/i4/3355153118/TB2UAadhHsTMeJjSsziXXcdwXXa_!!3355153118.jpg',
      itemBack: '//img.alicdn.com/imgextra/i1/3355153118/TB2agOvhHsTMeJjSszhXXcGCFXa_!!3355153118.jpg',
    },
    {
      modName: 'page6',
      itemCover: '//img.alicdn.com/imgextra/i4/3355153118/TB2UAadhHsTMeJjSsziXXcdwXXa_!!3355153118.jpg',
      itemBack: '//img.alicdn.com/imgextra/i1/3355153118/TB2agOvhHsTMeJjSszhXXcGCFXa_!!3355153118.jpg',
    },
    {
      modName: 'page7',
      itemCover: '//img.alicdn.com/imgextra/i4/3355153118/TB2UAadhHsTMeJjSsziXXcdwXXa_!!3355153118.jpg',
      itemBack: '//img.alicdn.com/imgextra/i1/3355153118/TB2agOvhHsTMeJjSszhXXcGCFXa_!!3355153118.jpg',
    },
  ],
  itemsHot: [
    {
      itemBack: 'https://img.alicdn.com/imgextra/i2/3355153118/TB2YtH0dr1YBuNjSszeXXablFXa-3355153118.jpg',
      url: 'http://tb.cn/2g2UDSw'
    },
  ],
  hasHot: 2,
  itemsErJi: [
    {
      itemBack: 'https://img.alicdn.com/imgextra/i3/3355153118/TB2CQ._dQKWBuNjy1zjXXcOypXa-3355153118.png',
      url: 'http://tb.cn/2g2UDSw'
    },
  ],

};

const styles = {
  wrapper: {
    width: 750,
    textAlign: 'center',
  },
};
class MainApp extends Component {
  constructor(props) {
    super(props);
    this.pageUtils = props.pageUtils;
    this.state = {
      mds: props.mds || {},
      gdc: props.gdc || {},
      selected: 0,
    };
    this.goToIndex = this.goToIndex.bind(this);
  }

  // 添加监听器，接收消息
  componentWillMount() {
    if (this.pageUtils && this.pageUtils.pageEmitter) {
      const emitter = this.pageUtils.pageEmitter;
      emitter.on('goToIndex', this.goToIndex);
    }

    // let { items } = this.state.mds.moduleData;
    // if (!items || !items.length || !items[0].itemBack || !items[0].itemBack.length) {
    //   items = defaultModuleData.items;
    // }
    // // console.log('items=1111==', items);
    // // 吸顶导航一开始发模块消息
    // items.forEach( item => {
    //   if (this.pageUtils && this.pageUtils.pageEmitter) {
    //     const emitter = this.pageUtils.pageEmitter;
    //     emitter.emit('clickTab', item.modName);
    //   }
    // });

  }





  // 组件销毁时移除监听器
  componentWillUnmount() {
    if (this.pageUtils && this.pageUtils.pageEmitter) {
      const emitter = this.pageUtils.pageEmitter;
      emitter.off('goToIndex', this.goToIndex);
    }
  }

  goToIndex() {
    this.clickItem({modName: 'page1'}, 0);
  }

  goTargetUrl = (url, nid) => {
    let { mds, gdc } = this.state;
    let params = {
      url: url,
      nid: nid || 0,
      widgetId: mds.widgetId,
      moduleName: mds.moduleName
    };

    this.pageUtils && this.pageUtils.goTargetUrl(params);
  };

  clickItem(item, index) {
    this.setState({
      selected: index,
    });
    if (this.pageUtils && this.pageUtils.pageEmitter) {
      const emitter = this.pageUtils.pageEmitter;
      emitter.emit('clickTab', item.modName);
    }
    if (this.pageUtils && this.pageUtils.lift) {
      const { widgetId } = this.state.mds;
      this.pageUtils.lift.scrollTo(widgetId);
    }
  }

  render() {
    const { selected, mds } = this.state;
    let {
      tabHeight,
      itemHeight,
      itemWidth,
      itemPadding,
      items,
      itemsHot,
      hasHot,
      itemsErJi,
      // showMore,
      // showMoreLink,
      // showMoreWidth,
    } = this.state.mds.moduleData;

    // 校正数据
    tabHeight = parseInt(tabHeight) || defaultModuleData.tabHeight;
    itemHeight = parseInt(itemHeight) || defaultModuleData.itemHeight;
    itemWidth = parseInt(itemWidth) || defaultModuleData.itemWidth;
    itemPadding = parseInt(itemPadding) || defaultModuleData.itemPadding;
    if (!items || !items.length || !items[0].itemBack || !items[0].itemBack.length) {
      items = defaultModuleData.items;
    }

    hasHot = parseInt(hasHot) || defaultModuleData.hasHot;

    if (!itemsHot || !itemsHot.length || !itemsHot[0].itemBack || !itemsHot[0].itemBack.length) {
      itemsHot = defaultModuleData.itemsHot;
    }
    if (!itemsErJi || !itemsErJi.length || !itemsErJi[0].itemBack || !itemsErJi[0].itemBack.length) {
      itemsErJi = defaultModuleData.itemsErJi;
    }


    // props
    const menuProps = {
      pageUtils: this.pageUtils,
      height: tabHeight,
      animated: true,
    };

    const tabHeaderProps = {
      selected,
      mds,
      height: tabHeight,
      itemHeight,
      itemWidth,
      itemPadding,
      items,
      clickItem: this.clickItem.bind(this),
      hasHot,
      itemsHot,
      itemsErJi,
      clickHot: (url, nid) => {
        this.goTargetUrl(url, nid);
      },

    };
    // const tipProps = {
    //   mds,
    //   img: showMore,
    //   link: showMoreLink,
    //   width: showMoreWidth,
    //   height: tabHeight,
    //   clickHot: (item, nid) => {
    //     this.goTargetUrl(item, nid);
    //   }
    // };

    return (
      <View data-role={mds.moduleName} data-spmc={`${mds.moduleName}_${mds.widgetId}`}>
        <MountingNavigation {...menuProps}>
          <View style={styles.wrapper}>
            <TabHeader {...tabHeaderProps}/>
            {/*<Tip {...tipProps}/>*/}
          </View>
        </MountingNavigation>
      </View>
    );
  }
}

const menuStyles = {
  topView: {
    zIndex: 999,
    width: 750,
    position: 'fixed',
    top: 0,
    backgroundColor: '#ffffff',
  },
  view: {
    backgroundColor: '#ffffff',
  }
};
class MountingNavigation extends Component {

  constructor(props) {
    super(props);
    this.pageUtils = props.pageUtils;
    this.state = {
      visibility: true
    };
  }

  onAppear = () => {
    this.setState({
      visibility: true
    });
    this.pageUtils.pageEmitter && this.pageUtils.pageEmitter.emit('fixTop', { state: true });
    this.props.onUnmounting && this.props.onUnmounting();
  };

  onDisappear = (e) => {
    if (e.direction === 'up') {
      this.setState({
        visibility: false
      });
      this.pageUtils.pageEmitter && this.pageUtils.pageEmitter.emit('fixTop', { state: false });
      this.props.onMounting && this.props.onMounting();
    }
  };

  render() {
    const { height = 100, animated = false, children } = this.props;
    // const { topView, tipBox } = menuStyles;

    const appearProps = {
      style: {
        height: 1,
        width: 750
      },
      onAppear: this.onAppear,
      onDisappear: this.onDisappear
    };
    const navProps = {
      animated,
      children
    };
    const noFixedProps = {
      ...navProps,
      style: {
        height,
        ...menuStyles.view,
      },
    };
    const fixedProps = {
      ...navProps,
      style: {
        height,
        ...menuStyles.topView,
      },
      isMount: false,
    };
    return ([
      !this.state.visibility ? <Nav {...fixedProps}/> : null,
      <Nav {...noFixedProps}/>,
      <View {...appearProps}/>,
    ]);
  }
}
class Nav extends Component {
  /**
   * 构建函数，处理传入的mds和gdc
   */
  constructor(props) {
    super(props);
    this.state = {
      firstTo: true
    };
  }

  componentDidMount() {
    const { isMount } = this.props;
    if (isMount) {
      const box = findDOMNode(this.refs.box); // 获取元素
      setTimeout(() => {
        transition(box, {
          opacity: 1
        }, {
          timingFunction: 'ease',
          duration: 500
        }, () => {
          this.setState({
            firstTo: false
          });
        });
      }, 0);
    }
  }

  render() {
    const {style, animated, children, isMount} = this.props;
    const { firstTo } = this.state;
    const props = {
      style: {
        ...style,
        opacity: isMount && firstTo && animated ? 0 : 1
      },
      ref: 'box'
    };
    return (
      <View {...props}>
        {children}
      </View>
    );
  }
}

const tabHeaderStyles = {
  boxStyle: {
    width: 750,
  },
  scrollStyle: {
    width: 750,
  },
};
class TabHeader extends Component {
  constructor(props) {
    super(props);
  }

  renderItem(item, index) {
    const { mds } = this.props;
    const { itemBack, itemCover } = item;
    const {
      selected,
      height,
      itemHeight,
      itemWidth,
      itemPadding,
      clickItem = () => {},
    } = this.props;
    const spmdId = `touchTop_${index}`;
    const spmd = `${mds.moduleName}_${mds.widgetId}_${spmdId}`;

    const touchProps = {
      key: `touchTop_${index}`,
      style: {
        width: itemWidth,
        height: itemHeight,
        marginLeft: index ? itemPadding : 0,
        marginTop: (height - itemHeight) / 2,
      },
      'data-spmd': spmd,
      onPress: () => {
        clickItem(item, index);
      }
    };
    const backProps = {
      source: {
        uri: selected === index ? itemCover : itemBack,
      },
      style: {
        width: itemWidth,
        height: itemHeight,
      },
      lazyload: true,
      resizeMode: 'cover',
    };

    return (
      <Touchable {...touchProps}>
        <Picture {...backProps}/>
      </Touchable>
    );
  }

  renderItemHot(item, index, ind) {
    const { mds } = this.props;
    const { itemBack, url, } = item;
    const {
      height,
      itemHeight,
      itemWidth,
      itemPadding,
      clickHot = () => {},
    } = this.props;
    const spmdId = `touch_${index}_${ind}`;
    const spmd = `${mds.moduleName}_${mds.widgetId}_${spmdId}`;

    const touchProps = {
      key: `touch_${index}_${ind}`,
      style: {
        width: itemWidth,
        height: itemHeight,
        marginLeft: index ? itemPadding : 0,
        marginTop: (height - itemHeight) / 2,
      },
      'data-spmd': spmd,
      onPress: () => {
        clickHot(url, spmdId);
      }
    };
    const backProps = {
      source: {
        uri: itemBack,
      },
      style: {
        width: itemWidth,
        height: itemHeight,
      },
      lazyload: true,
      resizeMode: 'cover',
    };

    return (
      <Touchable {...touchProps}>
        <Picture {...backProps}/>
      </Touchable>
    );
  }

  render() {
    const {
      height,
      items,

      hasHot,
      itemsHot,
      itemsErJi,
    } = this.props;
    // console.log(itemHeight, itemWidth, itemPadding, items);

    const scrollProps = {
      horizontal: true,
      showsVerticalScrollIndicator: false,
      showsHorizontalScrollIndicator: false,
      style: {
        height,
        ...tabHeaderStyles.scrollStyle,
      },
    };

    const itemArr = items.map((item, index) => this.renderItem(item, index));
    const hotArr = hasHot != 1 && itemsHot.map((item, index) => this.renderItemHot(item, index, 0));
    // console.log('hasHot===', hasHot);
    // console.log('hotArr===', hotArr);
    itemArr.splice(1, 0, hotArr);

    const erJiArr = itemsErJi.map((item, index) => this.renderItemHot(item, index, 1));
    itemArr.splice(itemArr.length - 1, 0, erJiArr);

    return (
      <View style={{
        height,
        ...tabHeaderStyles.boxStyle,
      }}>
        <ScrollView {...scrollProps}>
          {
            itemArr
          }
        </ScrollView>
      </View>
    );
  }
}

export default MainApp;

